package com.cwt_taxi_xa;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.model.RecorderInfo;
import com.cwt_taxi_xa.record.RecorderBiz;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.widget.timepicker.ScreenInfo;
import com.cwt_taxi_xa.widget.timepicker.WheelMain;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 收信箱信息界面
 *
 * @author ferch
 *
 */
public class RecordList extends CWTBaseActivity implements OnItemClickListener,
		OnTouchListener,OnClickListener {

	private static final String TAG = "RecordList";
	public TextView tips;
	public ListView listView;
	public List<RecorderInfo> list;
	private int lastItem;
	public View view;// 底部视图，加载更多
	TextView loadmore;
	public RecordAdapter adapter;
	private RecorderBiz biz;

	private TextView tv_count_all,tv_count_nomal,tv_count_complaint,tv_count_alarm,
			tv_time_start,tv_type,tv_time_end;

	private WheelMain wheelMain;
	private Calendar calendar;
	private Calendar calendarST;
	private Calendar calendarET;
	private int year;
	private int month;
	private int day;
	private int h;
	private int m;
	private AlertDialog dialogTime;
	private AlertDialog dialogType;

	private String[] types = new  String[] {"全部", "正常录音", "乘客投诉" , "报警录音"};

	private String startTime,// 开始时间
			endTime;// 结束时间
	/**
	 * 录音原因
	 * 0:正常录音 1:乘客不满意投诉 2：报警录音 3：全部
	 */
	private int witch = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record_list_bj);

		setupViews();
		addListener();
		initData();
	}

	private void addListener() {
		// TODO Auto-generated method stub
		listView.setOnItemClickListener(this);
		listView.setOnTouchListener(this);
		tips.setOnTouchListener(this);
		tv_type.setOnClickListener(this);
		tv_time_start.setOnClickListener(this);
		tv_time_end.setOnClickListener(this);
	}

	private void initData() {
		// TODO Auto-generated method stub
		tv_type.setText(types[witch]);
		changeTime();
		queryMessageCenter();
	}

	private void changeTime() {
		// TODO Auto-generated method stub
		String time = DateUtil.getTodayDate(DateUtil.df6);
		Date dateMeter = null;
		try {
			dateMeter = DateUtil.df6.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		calendar = Calendar.getInstance();
		calendarST = Calendar.getInstance();
		calendarET = Calendar.getInstance();
		calendar.setTime(dateMeter);
		calendarST.setTime(dateMeter);
		calendarET.setTime(dateMeter);
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		h = calendar.get(Calendar.HOUR_OF_DAY);
		m = calendar.get(Calendar.MINUTE);

		calendarST.set(year, month, day, 0, 0);
		Date date = calendarST.getTime();
		startTime = DateUtil.df13.format(date);
		tv_time_start.setText(startTime);

		calendarET.set(year, month, day, h, m);
		date = calendarET.getTime();
		endTime = DateUtil.df13.format(date);
		tv_time_end.setText(endTime);
	}

	private void setupViews() {
		// TODO Auto-generated method stub
		biz = new RecorderBiz(this);
		view = getLayoutInflater().inflate(R.layout.loadmore, null);
		tips = (TextView) this.findViewById(R.id.q_tip);
		listView = (ListView) this.findViewById(R.id.listView);
		listView.addFooterView(view);
		adapter = new RecordAdapter(this);
		loadmore = (TextView)view.findViewById(R.id.moreText);

		tv_count_all = (TextView) this.findViewById(R.id.tv_count_all);
		tv_count_nomal = (TextView) this.findViewById(R.id.tv_count_nomal);
		tv_count_complaint = (TextView) this.findViewById(R.id.tv_count_complaint);
		tv_count_alarm = (TextView) this.findViewById(R.id.tv_count_alarm);
		tv_type = (TextView) this.findViewById(R.id.tv_type);
		tv_time_start = (TextView) this.findViewById(R.id.tv_time_start);
		tv_time_end = (TextView) this.findViewById(R.id.tv_time_end);
	}

	protected void doType() {
		// TODO Auto-generated method stub
		if(dialogType == null){
			dialogType = new  AlertDialog.Builder(this)
					.setTitle("录音原因" )
					.setIcon(android.R.drawable.ic_dialog_info)
					.setMultiChoiceItems(types,  null ,  null )
					.setSingleChoiceItems(types, witch, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int witch) {
							// TODO Auto-generated method stub
							RecordList.this.witch = witch;
							tv_type.setText(types[witch]);
							dataCount();
							dialog.dismiss();
						}
					})
					.setNegativeButton("取消" ,  new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int arg1) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					})
					.show();
		}else{
			dialogType.show();
		}
	}

	/** 选择时间*/
	private void choiceTime(final TextView tv) {
		// TODO Auto-generated method stub
		String title = "";
		if(tv.getId() == R.id.tv_time_start){
			title = "设置开始时间";
			calendar = calendarST;
		}else{
			calendar = calendarET;
			title = "设置结束时间";
		}
		LayoutInflater inflater = LayoutInflater.from(this);
		final View timepickerview = inflater.inflate(R.layout.datepicker,
				null);
		ScreenInfo screenInfo = new ScreenInfo(this);
		wheelMain = new WheelMain(timepickerview, true);
		wheelMain.screenheight = screenInfo.getHeight();

		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		h = calendar.get(Calendar.HOUR_OF_DAY);
		m = calendar.get(Calendar.MINUTE);

		wheelMain.initDateTimePicker(year, month, day, h, m);
		wheelMain.setTextSize(26, 30);
		new AlertDialog.Builder(this)
				.setTitle(title)
				.setView(timepickerview)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//				tv.setText(wheelMain.getTime());
						tv.setText(DateUtil.dateFormatForTimePicker(wheelMain.getTime()));
						try {
							if(tv.getId() == R.id.tv_time_start){
								startTime = tv_time_start.getText().toString();
								long sTime = DateUtil.df13.parse(startTime).getTime();
								calendarST.setTimeInMillis(sTime);
							}else{
								endTime = tv_time_end.getText().toString();
								long eTime = DateUtil.df13.parse(endTime).getTime();
								calendarET.setTimeInMillis(eTime);
							}
							queryMessageCenter();
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						dialog.dismiss();
					}
				})
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						}).show();
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 查找第一次的数据
	 */
	public void queryMessageCenter() {
		new AsyncTask<String, Integer, Long>() {
			@Override
			protected Long doInBackground(String... params) {
				String sTime = DateUtil.getTime(startTime, DateUtil.df13, DateUtil.df8);
				String eTime = DateUtil.getTime(endTime, DateUtil.df13, DateUtil.df8);
				list = biz.findInfos(witch-1, sTime, eTime);
				return 1L;
			}

			@Override
			protected void onPostExecute(Long result) {
				dataCount();
			}
		}.execute();
	}
	protected void dataCount() {
		// TODO Auto-generated method stub
		int countAll = 0,countNomal = 0,countComplaint = 0,countAlarm = 0;
		ArrayList<RecorderInfo> showList = null;
		if(list != null && list.size() != 0){
			showList = new ArrayList<RecorderInfo>();
			for(int i = 0;i<list.size();i++){
				RecorderInfo info = list.get(i);
				/**
				 * 录音原因
				 * 0:正常录音 1:乘客不满意投诉 2：报警录音
				 */
				int reason = info.getReason();
				if(reason == 0){// 正常录音
					if(witch == 0 || witch == 1){
						countNomal++;
						showList.add(info);
					}
				}else if(reason == 1){// 乘客不满意投诉
					if(witch == 0 || witch == 2){
						countComplaint++;
						showList.add(info);
					}
				}else if(reason == 2){// 报警录音
					if(witch == 0 || witch == 3){
						countAlarm++;
						showList.add(info);
					}
				}
			}
		}
		countAll = countNomal + countComplaint + countAlarm;
		tv_count_all.setText(String.valueOf(countAll));
		tv_count_nomal.setText(String.valueOf(countNomal));
		tv_count_complaint.setText(String.valueOf(countComplaint));
		tv_count_alarm.setText(String.valueOf(countAlarm));

		if (showList != null && showList.size() > 0) {
			tips.setVisibility(View.GONE);
			adapter.setData(showList);
			listView.setAdapter(adapter);
			listView.removeFooterView(view);
		} else {
			tips.setText("暂无数据!");
			tips.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 各个item点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		//arg2
		String oldPath = Constants.RECORDING_PATH+"/"+list.get(arg2).getTime()+".mp3";
		File photoFile = new File(oldPath);
		if(photoFile.exists()){
			Uri uri = Uri.parse("file://"+oldPath);

			Intent mIntent = new Intent();
			mIntent.setAction(android.content.Intent.ACTION_VIEW);
			mIntent.setDataAndType(uri , "audio/*");
			startActivity(mIntent);


//			Intent intent = new Intent(Intent.ACTION_MAIN);
//			intent.setAction(Intent.ACTION_DEFAULT);
//			// intent.addCategory(Intent.CATEGORY_APP_MUSIC);
//			intent.setDataAndType(uri, "audio/*");
//			startActivity(intent);


		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(dialogTime != null && dialogTime.isShowing()){
			dialogTime.dismiss();
		}
		if(dialogType != null && dialogType.isShowing()){
			dialogType.dismiss();
		}
	}

	public class RecordAdapter extends BaseAdapter{
		private static final String TAG = "MessageAdapter.";
		public Context context;
		private LayoutInflater mInflater=null;
		private List<RecorderInfo> list;
		private RecorderInfo info;

		public RecordAdapter(Context context) {
			this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if(null!=list&&list.size()>0){
				return list.size();
			}

			return 0;
		}

		public void setData(List<RecorderInfo> list) {
			this.list = list;
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		public void addItems(List<RecorderInfo> nlist) {
			for (int i = 0; i < nlist.size(); i++) {
				this.list.add(nlist.get(i));
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {

				ViewHolder viewHolder = null;
				if(convertView == null){
					convertView = mInflater.inflate(R.layout.record_item, null);
					viewHolder = new ViewHolder();
					viewHolder.tv_time_start = (TextView) convertView.findViewById(R.id.tv_time_start);
					viewHolder.tv_time_end = (TextView) convertView.findViewById(R.id.tv_time_end);
					viewHolder.tv_time_len = (TextView) convertView.findViewById(R.id.tv_time_len);
					viewHolder.tv_reason = (TextView) convertView.findViewById(R.id.tv_reason);
					viewHolder.tv_file_name = (TextView) convertView.findViewById(R.id.tv_file_name);
					viewHolder.tv_media_id = (TextView) convertView.findViewById(R.id.tv_media_id);
					viewHolder.tv_create_time = (TextView) convertView.findViewById(R.id.tv_create_time);
					convertView.setTag(viewHolder);
				}else{
					viewHolder = (ViewHolder) convertView.getTag();
				}
				info = list.get(position);

				String sTime = DateUtil.getTime(info.getTime(), DateUtil.df8, DateUtil.df12);
				viewHolder.tv_time_start.setText(sTime);

				String eTime = DateUtil.getTime(info.getEtime(), DateUtil.df6, DateUtil.df12);
				viewHolder.tv_time_end.setText(eTime);

				String cTime = DateUtil.getTime("20"+info.getTime(), DateUtil.df6, DateUtil.df1);
				cTime = DateUtil.getShowTime(cTime);
				viewHolder.tv_create_time.setText(cTime);
				viewHolder.tv_media_id.setText(info.getMediaId());
				viewHolder.tv_file_name.setText(info.getTime()+".mp3");

				long sTimeMis = DateUtil.getTimeMillis(DateUtil.df6, "20"+info.getTime());
				long eTimeMis = DateUtil.getTimeMillis(DateUtil.df6, info.getEtime());
				long timeBetween = eTimeMis - sTimeMis;
				String showTimeBetween = DateUtil.sec2Time((int)(timeBetween / 1000));
				viewHolder.tv_time_len.setText(showTimeBetween);

				int reason = info.getReason();
				if(reason == 0){
					viewHolder.tv_reason.setText("正常录音");
				}else if(reason == 1){
					viewHolder.tv_reason.setText("投诉录音");
				}else if(reason == 2){
					viewHolder.tv_reason.setText("报警录音");
				}
				return convertView;

			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e), e);
				e.printStackTrace();
				return null;
			}
		}
	}

	class ViewHolder{
		private TextView tv_time_start;
		private TextView tv_time_end;
		private TextView tv_time_len;
		private TextView tv_reason;
		private TextView tv_file_name;
		private TextView tv_media_id;
		private TextView tv_create_time;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.tv_type:
				doType();
				break;
			case R.id.tv_time_start:
				choiceTime(tv_time_start);
				break;
			case R.id.tv_time_end:
				choiceTime(tv_time_end);
				break;

			default:
				break;
		}
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}
}